package com.harry.hr.dao.impl;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.harry.hr.dao.MenuDAO;
import com.harry.hr.entity.system.Menu;
import com.harry.hr.entity.system.Role;

public class MenuDAOImpl extends HibernateDaoSupport implements MenuDAO {

	public void clear(Menu menu) {
		this.getHibernateTemplate().delete(menu);
	}

	public void delete(Menu menu) {
		menu=(Menu)this.getHibernateTemplate().get(Menu.class, menu.getMenuId());
		menu.setMenuStatus(false);
		update(menu);
	}

	@SuppressWarnings("unchecked")
	public List<Menu> query(Role role) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Menu.class);
		if(role!=null){
			if(role.getRoleId()>0)
				criteria.createCriteria("roles").add(Restrictions.idEq(role.getRoleId()));
			criteria.add(Restrictions.eq("menuStatus", true));
		} 
		criteria.addOrder(Order.desc("menuOrder"));
		return this.getHibernateTemplate().findByCriteria(criteria);
	}
	
	
	@SuppressWarnings("unchecked")
	public List<Menu> query(Menu menu,MatchMode mode,Order order){
		DetachedCriteria criteria = DetachedCriteria.forClass(Menu.class);
		if(mode==null)
			mode=MatchMode.ANYWHERE;
		if(menu!=null){
			if(menu.getMenuTitle()!=null&&menu.getMenuTitle()!="")
				criteria.add(Restrictions.like("menuTitle",menu.getMenuTitle(),mode));
			if(menu.getMenuUpId()>0)
				criteria.add(Restrictions.eq("menuUpId",menu.getMenuUpId()));
			if(menu.getMenuRemark()!=null&&menu.getMenuRemark()!="")	
				criteria.add(Restrictions.eq("menuRemark",menu.getMenuRemark()));
			criteria.add(Restrictions.eq("menuStatus",menu.getMenuStatus()));
		}else{
			criteria.add(Restrictions.eq("menuStatus",true));
		}
		if(order!=null)
			criteria.addOrder(order);
		return this.getHibernateTemplate().findByCriteria(criteria);
	}
	
	public void save(Menu menu) {
		this.getHibernateTemplate().save(menu);
		
	}

	public void update(Menu menu) {
		this.getHibernateTemplate().update(menu);
		
	}

	public Menu getById(int id) {
		return (Menu)this.getHibernateTemplate().get(Menu.class, id);
	}

}
